//
//  XMAddressListViewController.m
//  XunMi
//
//  Created by MacBook on 2024/3/5.
//  Copyright © 2024 TieZhu. All rights reserved.
//

#import "XMAddressListViewController.h"
#import "XMAddressTableViewCell.h"
#import "XMAddressFooterView.h"
#import "XMAddressAddViewController.h"
#import "XMAddressModel.h"

@interface XMAddressListViewController ()
@property (nonatomic, strong) NSMutableArray <XMAddressModel *> *dataArray;
@property (nonatomic, strong) XMAddressFooterView *footerV;
@property (nonatomic, assign) BOOL isEdit;
@end

@implementation XMAddressListViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self initVariables];
    [self setupSubviews];
    [self addressListData];
    [self viewBlock];
}

#pragma mark - 初始化变量
- (void)initVariables {
    [self tableViewRegisterNibWithNibName:kStringFromClass(XMAddressTableViewCell)];
    self.dataArray = [NSMutableArray array];
}

- (void)addressListData {
    self.navRightBtn.selected = NO;
    [MBProgressHUD showHUDActivityMsg:nil];
    [self.dataArray removeAllObjects];
    NSMutableDictionary *dic = @{
    }.mutableCopy;
    
    [YHNetworkManager.sharedInstance postWithUrl:@"api/address/obtain" parameters:dic completeBlock:^(XMResponseTip * _Nonnull tip, id  _Nullable result) {
        if (tip.success) {
            [MBProgressHUD hideHUD];
            NSArray *record = [result safe_objectForKey:@"record"];
            NSArray *array = [XMAddressModel mj_objectArrayWithKeyValuesArray:record];
            [self.dataArray addObjectsFromArray:array];
            
        }
        [self.tableView reloadData];
        [self.tableView.mj_header endRefreshing];
        self.tableView.mj_footer.hidden = self.dataArray.count == 0;
        if (tip.loadMore) {
            [self.tableView.mj_footer endRefreshing];
        } else {
            [self.tableView.mj_footer endRefreshingWithNoMoreData];
        }
    }];
}

#pragma mark - setupSubViews
- (void)setupSubviews {
    self.navView.backgroundColor = kHEX(@"#F2F2F2");
    self.view.backgroundColor = kHEX(@"#F2F2F2");
    self.tableView.backgroundColor = kHEX(@"#F2F2F2");
    [self.tableView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.view).insets(UIEdgeInsetsMake(kNavBarAndStatusBarHeight, 0, kBottomSafeHeight, 0));
    }];
    [self.navLeft2Btn setTitle:@"地址管理" forState:UIControlStateNormal];
    [self.navRightBtn setImage:kGetImage(@"addr_r") forState:UIControlStateNormal];
    [self.navRightBtn addTarget:self action:@selector(edit:) forControlEvents:UIControlEventTouchUpInside];
    UIView *v = [[UIView alloc] initWithFrame:kFRAME(0, 0, kScreenWidth, 100)];
    self.footerV = [XMAddressFooterView viewFromXib];
    self.tableView.tableFooterView = v;
    [v addSubview:_footerV];
}

- (void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];
    self.footerV.frame = kFRAME(0, 0, kScreenWidth, 100);
}

#pragma mark - viewBlock
- (void)viewBlock {
    XMWeakSelf(self);
    self.footerV.addBlock = ^{
        XMStrongSelf(self);
        XMAddressAddViewController *vc = [[XMAddressAddViewController alloc] initWithNibName:kStringFromClass(XMAddressAddViewController) bundle:nil];
        vc.type = XMAddressHandleTypeAdd;
        XMWeakSelf(self);
        vc.saveBlock = ^{
            XMStrongSelf(self);
            [self addressListData];
        };
        [self.navigationController pushViewController:vc animated:YES];
    };
}
#pragma mark - Actions
- (void)edit:(UIButton *)sender {
    sender.selected = !sender.selected;
    [self.dataArray enumerateObjectsUsingBlock:^(XMAddressModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        obj.isEdit = sender.selected;
    }];
    [self.tableView reloadData];
}

#pragma mark - UITableViewDataSource & UITableViewDelegate

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    XMAddressTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kStringFromClass(XMAddressTableViewCell)];
    XMAddressModel *model = [self.dataArray safe_objectAtIndex:indexPath.row];
    cell.model = model;
    
    XMWeakSelf(self);
    cell.defBlock = ^(XMAddressModel * _Nonnull model) {
        XMStrongSelf(self);
        [MBProgressHUD showHUDActivityMsg:nil toView:kWindow];
        NSMutableDictionary *dic = @{
            @"index": model.index
        }.mutableCopy;
        
        [YHNetworkManager.sharedInstance postWithUrl:@"api/address/updateDefaultStatus" parameters:dic completeBlock:^(XMResponseTip * _Nonnull tip, id  _Nullable result) {
            if (tip.success) {
                [MBProgressHUD hideHUD];
                [self addressListData];
            }
        }];
    };
    
    cell.deleteBlock = ^(XMAddressModel * _Nonnull model) {
        XMStrongSelf(self);
        [MBProgressHUD showHUDActivityMsg:nil toView:kWindow];
        NSMutableDictionary *dic = @{
            @"index": model.index
        }.mutableCopy;
        [YHNetworkManager.sharedInstance postWithUrl:@"api/address/delete" parameters:dic completeBlock:^(XMResponseTip * _Nonnull tip, id  _Nullable result) {
            if (tip.success) {
                [MBProgressHUD hideHUD];
                [self addressListData];
            }
        }];
    };
    
    cell.detailBlock = ^(XMAddressModel * _Nonnull model) {
        XMStrongSelf(self);
        XMAddressAddViewController *vc = [[XMAddressAddViewController alloc] initWithNibName:kStringFromClass(XMAddressAddViewController) bundle:nil];
        vc.model = model;
        vc.type = XMAddressHandleTypeEdit;
        XMWeakSelf(self);
        vc.saveBlock = ^{
            XMStrongSelf(self);
            [self addressListData];
        };
        [self.navigationController pushViewController:vc animated:YES];
    };
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 100;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return CGFLOAT_MIN;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    return nil;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    return nil;
}

@end
